// 为接口设置当前用户
const {db, QueryTypes} = require("../models/db");
const tool = require('../tools/tool')
const setUser = async (ctx, next) => {
    if(ctx.request.headers.token) {
        if(ctx.request.url !=='/user/login') {
            try {
                let sql = `select a.id,a.username,a.name,a.tenantId,a.roleId,a.token,a.allData,a.selfData,a.autoLeft,b.name roleName,
                                  a.printHead,isNull(t.isCard,0) as isCard,a.buId from (
                    select id, username, name,tenantId,roleId,token,allData,selfData,autoLeft,printHead,isnull(buId,0) buId from admin  where token='${ctx.request.headers.token}'
                ) a left join role b on a.roleId=b.id left join tenant t on a.tenantId=t.id `
                let user = await db.query(sql, {type:QueryTypes.SELECT, plain: true});

                if(!user) {
                    return ctx.err('登录过期,请重新登录')
                }
                else {
                    ctx.user = user
                }
            } catch (e) {
                await db.models['logExKoa'].create({
                    api: 'cell.js,用户验证',
                    msg: e.toString(),
                    ct: tool.getTime()
                })
                return ctx.err('用户验证失败')
            }
        }
    }
    await next();
}

module.exports = setUser